package com.atstudying.mall.mallauthserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atstudying.common.constant.AuthServerConstant;
import com.atstudying.common.utils.HttpUtils;
import com.atstudying.common.utils.R;
import com.atstudying.mall.mallauthserver.feign.MemberFeignService;
import com.atstudying.common.vo.MemberRespVo;
import com.atstudying.mall.mallauthserver.vo.SocicalUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.zhneg
 * @create 2020-11-13-22:42
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;
    //http://auth.mall.com/oauth2.0/weibo/sucess?code=618dd991afe06e0dd397058383f8c050
    @GetMapping("/oauth2.0/weibo/sucess")
    public String weibo(@RequestParam("code") String code, RedirectAttributes redirectAttributes, HttpSession session) throws Exception {

        //https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID
        // &client_secret=YOUR_CLIENT_SECRET
        // &grant_type=authorization_code
        // &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
        // &code=CODE
        //1：根据code换取accessToken
        Map<String,String> map=new HashMap<>();
        map.put("client_id","258385928");
        map.put("client_secret","7950ff21002cdb2bc5992d8d8fd11a77");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.mall.com/oauth2.0/weibo/sucess");
        map.put("code",code);
        //消息请求头Headers
        Map<String, String> headersMap = new HashMap<String, String>();
        headersMap.put("sign","加密后的签名");

//        headersMap.put("Content-Type","application/json; charset=utf-8");
        HttpResponse response = HttpUtils.doPost("api.weibo.com", "/oauth2/access_token", "post",headersMap, null, map);
        //2：处理
        if (response.getStatusLine().getStatusCode()==200){

            /**获取到的响应（access_token)通过得到code
             * {
             "access_token": "2.00ZXZCqG0yyJUR39ec702bd5Indy3D",
             "remind_in": "157679999",
             "expires_in": 157679999,
             "uid": "6265779741",
             "isRealName": "true"
             }
             */
            //获取到accessToken
          String json=  EntityUtils.toString(response.getEntity());
          //把json字符串转化成SocicalUser
            SocicalUser socicalUser = JSON.parseObject(json, SocicalUser.class);

            //知道当前是哪个社交用户
            //1）当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R login = memberFeignService.oauth2login(socicalUser);
            if (login.getCode()==0){

                //MemberRespVo数据要实现序列化，存储到redis里面
                MemberRespVo data = login.getData("data",new TypeReference<MemberRespVo>() {
                });

                //第一次使用session：命令浏览器保存卡号 JSESSIONID这个cookie
                //以后浏览器访问那个网站就会带上这个网站的cookie
                //子域之间 zlj.mall.com auth.mall.com order.mall.com
                //发卡的时候（指定域名为父域名）即使是子域系统发的卡，也可以让父域直接使用

                //todo 1：默认发的令牌：session=dsajkdjl：作用域：当前域（必须解决子域session共享问题）
                //todo 2：使用json的序列化方式来序列化对象到redis中
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                log.info("登录成功：用户{}"+data.toString());
                //成功
                return "redirect:http://zlj.mall.com";

            }else {

                HashMap<String,String> errors=new HashMap<>();
                errors.put("errors",login.getData("msg",new TypeReference<String>(){}));

                redirectAttributes.addFlashAttribute("errors",errors);
                //失败！！！
                return "redirect:http://auth.mall.com/login.html";
            }

        }else {
            return "redirect:http://auth.mall.com/login.html";

        }

//        //3登录成功就跳回首页
//
//        return "redirect:http://zlj.mall.com";
    }
}
